package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"path/filepath"
	"strings"
	"time"
	"video/models"
)

type VideoController struct {
	beego.Controller
}
type JsonData struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *VideoController) Add() {
	title := c.GetString("title")
	intro := c.GetString("intro")
	img := c.GetString("img")
	times := time.Now()
	user := c.GetString("user")
	video := models.Video{
		Title: title,
		Intro: intro,
		Img:   img,
		Times: times,
		User:  user,
	}

	err := models.DB.Create(&video).Error
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonData{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *VideoController) List() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 3)
	name := c.GetString("name")
	video, total, err := models.MysqlList(page, pageSize, name)
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "分页失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		JsonMsg := make(map[string]interface{})
		JsonMsg["video"] = video
		JsonMsg["total"] = total
		c.Data["json"] = JsonData{
			Code: 200,
			Msg:  "分页成功",
			Data: JsonMsg,
		}
		c.ServeJSON()
	}
}
func (c *VideoController) Del() {
	id, _ := c.GetInt("id")
	video := models.Video{
		Id: id,
	}
	err := models.DB.Delete(&video).Error
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonData{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *VideoController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "文件获取失败",
			Data: nil,
		}
		return
	}
	defer file.Close()
	if header.Size > 5*1024*1024 {
		c.Data["josn"] = JsonData{
			Code: 500,
			Msg:  "文件大小不对",
			Data: nil,
		}
		c.ServeJSON()
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	suffixMax := map[string]bool{
		".png": true,
		".jpg": true,
	}
	if !suffixMax[suffix] {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "文件格式不对",
			Data: nil,
		}
		c.ServeJSON()
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "文件上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		ImgSrc := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonData{
			Code: 200,
			Msg:  "文件上传成功",
			Data: ImgSrc,
		}
		c.ServeJSON()
	}

}
